package com.nd.fastdp.framework.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.nd.fastdp.framework.pojo.bo.LoginUser;
import com.nd.fastdp.utils.CustomCellWriteHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author: lxc
 * @Date: 2020/09/26 17:20:46
 * @Version: 1.0
 * @Description: 导出
 */
public abstract class ExcelExportHandler extends ExportHandler{

    @Override
    public void execute(LoginUser loginUser, Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) {

        ExcelWriter excelWriter = null;
        try {

            OutputStream out = getOutputStream(getFileName(), response);
            Class template = getTemplate();

            excelWriter = EasyExcel.write(out, template).excelType(ExcelTypeEnum.XLSX).registerWriteHandler(new CustomCellWriteHandler()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.write(getData(loginUser, param, request), writeSheet);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    protected abstract List getData(LoginUser loginUser, Map<String, Object> param, HttpServletRequest request);

    protected abstract Class getTemplate();

    protected abstract String getFileName();

    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
